package com.mirror.tk.core.sms.template.impl;

import java.io.StringWriter;
import java.util.Arrays;

import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.mirror.tk.core.module.sys.service.BasicService;
import com.mirror.tk.core.sms.template.TemplateService;

public class DbTemplateServiceImpl implements TemplateService {

	private VelocityEngine velocityEngine = new VelocityEngine();
	private BasicService basicService;

	@Override
	public String getTemplate(String code) {
		return basicService.getSmsTpl(code);
	}

	@Override
	public String mergeTemplate(String code, String... params) {
		String template = getTemplate(code);
		if (StringUtils.isBlank(template)) {
			throw new RuntimeException("Template Code[" + code + "] Does not exist");
		}

		VelocityContext context = new VelocityContext();
		context.put("msg", Arrays.asList(params));
		StringWriter writer = new StringWriter();
		velocityEngine.evaluate(context, writer, "error", template);
		return writer.toString();
	}

	public BasicService getBasicService() {
		return basicService;
	}

	public void setBasicService(BasicService basicService) {
		this.basicService = basicService;
	}

}
